package com.scau.bookstore.api.util;

import com.aliyun.oss.OSSClient;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.*;

public class FileUtil {
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    private String accessKeyId = "LTAIfi8teV3C3nwn";
    private String accessKeySecret = "wclLff3TFMLFZIG1Mko9UpKGGsAK6v";
    private String bucketName = "scau-bookstore";

    // 创建OSSClient实例。
    private OSSClient ossClient;

    public void before() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    public void after() {
        ossClient.shutdown();
    }

    public String upload(MultipartFile file) {
        try {
            before();
            String objectName = UUID.randomUUID().toString().replace("-", "") + "-" + file.getName();
            String fileName = objectName;
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()){
                path = new File("");
            }
            File uploadPath = new File(path.getAbsolutePath(), "static/");
            if (!uploadPath.exists()){
                uploadPath.mkdirs();
            }
            File tempFile = new File(uploadPath, fileName);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();//创建父级文件路径
                tempFile.createNewFile();//创建文件
            }
            file.transferTo(tempFile);
            System.out.println(tempFile.getAbsolutePath());
            // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            ossClient.putObject(bucketName, objectName, tempFile);
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);

            //TODO 删除临时文件
            tempFile.delete();
            return url.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            after();
        }
        return "";
    }

}
